<?php
/**
 *
 * Project:     Neuf TV MediaCenter - MP9CTL
 * File:        config.php
 *
 * Configuration dossiers & lecteurs favoris
 *
 * @author David G. pour Neuf Cegetel
 *
 */

/* Fonctions communes */
require_once('common.inc.php');

/* Detection soumission selection */
if (isset($_POST['file'])) {
    if ($_POST['file'] == 'file1') {
	header('Content-Type: text/plain'); 
	header('Content-Disposition: attachment; filename="shares.conf"');
	print("<?php\n");
	$id = 1;
	if (isset($_POST['folder']) || isset($_POST['device'])) {
	    if (isset($_POST['folder'])) {
		foreach($_POST['folder'] as $folder) {
		    $folder = rtrim($folder, "\\/");
		    print("addShareFolder($id, \"".basename($folder)."\", \"$folder\");\n"); 
		    $id++;
		}
	    }
	    if (isset($_POST['device'])) {
		foreach($_POST['device'] as $device) {
		    $device = rtrim($device, "\\/");
		    print("addShareDevice($id, \"".basename($device)."\", \"$device\", DEVICE_HARDDISK, TRUE);\n"); 
		    $id++;
		}
	    }
	} else if (isset($_POST['selected'])) {
	    for($i=0; $i<count($_POST['selected']); $i++) {
		$folder = rtrim(urldecode($_POST['selected'][$i]), "\\/");
		print("addShareFolder($id, \"".basename($folder)."\", \"$folder\");\n"); 
		$id++;
	    }
	}
	print("?>\n");
	exit();
    }
    else if ($_POST['file'] == 'file2') {
	header('Content-Type: text/plain'); 
	header('Content-Disposition: attachment; filename="httpshares.conf"');
	$id = 1;
	if (isset($_POST['folder']) || isset($_POST['device'])) {
	    if (isset($_POST['folder'])) {
		foreach($_POST['folder'] as $folder) {
		    $folder = rtrim($folder, "\\/");
		    $folder = str_replace('\\\\', '/', $folder);
		    print("Alias /".SHARE_PREFIX.$id."/ \"$folder/\"\n"); 
		    $id++;
		}
	    }
	    if (isset($_POST['device'])) {
		foreach($_POST['device'] as $device) {
		    $device = rtrim($device, "\\/");
		    $device = str_replace('\\\\', '/', $device);
		    print("Alias /".SHARE_PREFIX.$id."/ \"$device/\"\n"); 
		    $id++;
		}
	    }
	} else if (isset($_POST['selected'])) {
	    for($i=0; $i<count($_POST['selected']); $i++) {
		$folder = rtrim(urldecode($_POST['selected'][$i]), "\\/");
		print("Alias /".SHARE_PREFIX.$id."/ \"$folder/\"\n"); 
		$id++;
	    }
	}
	exit();
    }
    exit();
}

/*** Fonctions de parcours repertoires ********************************/

/* Parcours recursif repertoire */
function getDirContent($name, $depth = 0) {
    if (substr($name, -1, 1) != '/') $name .= '/';
    $content = array();
    if ($depth < BROWSE_MAX_DEPTH && $dir = @dir($name)) {
	while ($file = $dir->read()) {
	    if (isUsableFileOrDir($name.$file) && @is_dir($name.$file) && !@is_link($name.$file)) {
		$c = array();
		$c['name'] = $file;
		$c['path'] = $name.$file;
		$c['subdir'] = getDirContent($c['path'], $depth+1);
		$content[] = $c;
	    }
	}
    } else {
	$content = FALSE;
    }
    return $content;
}

/* Parcours lecteurs */
function getDrivesContent() {
    global $drives, $folders;
    foreach($drives as $d) {
	if (is_dir($d) && is_readable($d)) {
	    $f = array();
	    $f['name'] = $d;
	    $f['path'] = $d;
	    $f['subdir'] = getDirContent($d);
	    $folders[] = $f;
	}
    }
}

/* Dossier inclus dans la configuration actuelle */
function isSelected($path) {
    global $shares;
    reset($shares);
    foreach($shares as $share) {
	if (str_replace('\\','/',strtolower($share['path'])) == strtolower($path)) return TRUE;
    }
    return FALSE;
}

/* Affichage dossiers */
$id = 1;
function printFolder($folder, $depth = 0) {
    global $id;
    for ($i=0; $i<count($folder); $i++) {
	if ($folder[$i]['subdir']) {
	    print(str_repeat('<div class="plus">&nbsp;</div>', $depth).'<a class="plus" href="Javascript:toggle(\'f'.$id.'\');">+</a><input type="checkbox" name="selected[]" value="'.urlencode(str_replace('\\','/',stripslashes($folder[$i]['path']))).'" '.(isSelected($folder[$i]['path'])?'checked ':'').'/>'.$folder[$i]['name'].'<br/>');
	    print('<div id="f'.$id.'" style="display: none">');
	    $id++;
	    printFolder($folder[$i]['subdir'], $depth+1);
	    print('</div>');
	} else {
	    print(str_repeat('<div class="plus">&nbsp;</div>', $depth+1).'<input type="checkbox" name="selected[]" value="'.urlencode(str_replace('\\','/',stripslashes($folder[$i]['path']))).'" '.(isSelected($folder[$i]['path'])?'checked ':'').'/>'.$folder[$i]['name'].'<br/>');
	}
    }
}

/**********************************************************************/

/* Definition des partages */
require(getConfFile());

/* Limite d'execution a 180 sec. pour parcours complet */
set_time_limit(200);

/* Parametres */
$useFoldersTree = (isset($_GET['mode']) && $_GET['mode'] == 'tree' ? TRUE : FALSE);

/* Liste lecteurs de C a Z si windows, '/' si autre */
if (getOSType() == 'windows') {
    $drives = array(); for($i=2; $i<26; $i++) { $drives[] = chr(ord('A')+$i).':'; }
} else if (getOSType() == 'macos') {
    $drives = array('/Users', '/Volumes');
} else {
    $drives = array('/');
}
$folders = array();

/* Repertoires d'ecriture des fichiers */
switch (getOSType()) {
    case 'windows':
	$configFile1 = 'Mediacenter/data/';
	$configFile2 = 'Mediacenter/data/';
	break;

    case 'macos':
	$configFile1 = 'Mediacenter/data/';
	$configFile2 = 'Mediacenter/data/';
	break;

    case 'linux':
	$configFile1 = 'data/';
	$configFile2 = 'data/';
	break;

    default:
	$configFile1 = 'data/';
	$configFile2 = 'data/';
}

?>
<html>
    <head>
	<title>MediaCenter - Neuf TV HD</title>
	<link rel="StyleSheet" href="../style.css" type="text/css" />
	<script>
	function toggle(id) {
	    document.getElementById(id).style.display = (document.getElementById(id).style.display == "block" ? "none" : "block");
	}
	function addRow(table, tdlist) {
	    var tbody = table.tBodies[0];
	    var newRow = tbody.insertRow(-1);
	    for(var i=0; i<tdlist.length; i++) {
		var cell = newRow.insertCell(i);
	       	cell.innerHTML = tdlist[i];
	    }
	}
	function deleteRows(table) {
	    var tbody = table.tBodies[0];
	    while(tbody.rows.length > 0) {
		tbody.deleteRow(0);
	    }
	}
	function addFolder(folder) {
	    if (!folder) folder = document.getElementById("form").folderName.value;
	    if (folder == '') return false;
	    shares.push({path: folder});
	    document.getElementById("form").folderName.value = "";
	    addRow(document.getElementById("foldersList"), new Array(shares.length,folder,'<input type="button" value="Supprimer" onClick="deleteShare('+shares.length+')" />'));
	    var newInput = document.createElement("input");
	    newInput.setAttribute("type", "hidden");
	    newInput.setAttribute("name", "folder[]");
	    newInput.setAttribute("value", folder);
	    document.forms["form"].appendChild(newInput);
	}
	function deleteShare(id) {
	    shares.splice(id-1,1);
	    refreshShares();
	}
	function refreshShares() {
	    prevShares = shares.slice();
	    shares = new Array();
	    deleteRows(document.getElementById("foldersList"));
	    document.getElementById("foldersListValue").innerHTML = "";
	    for(var i=0; i<prevShares.length; i++) {
		addFolder(prevShares[i].path, true);
	    }
	}
	function createFile(file) {
	    if (document.getElementById("addFolderButton")) document.getElementById("addFolderButton").disabled = true;
	    if (document.getElementById("addDeviceButton")) document.getElementById("addDeviceButton").disabled = true;

	    if (file == 'file1') {
		document.getElementById("createFile1").style.display = "none";
		document.getElementById("form").file.value = 'file1';
	    } else if (file == 'file2') {
		document.getElementById("createFile2").style.display = "none";
		document.getElementById("form").file.value = 'file2';
	    }
	    return document.getElementById("form").submit();
	}
	var shares = new Array();
	var prevShares = new Array();
<?php foreach($shares as $share) { ?>
    	prevShares.push( {name: '<?= $share['name'] ?>', path: '<?= addslashes($share['path']) ?>' });
<?php } ?>
    	function init() {
	    if (!location.href.match(/mode=tree/)) {
		for(var i=0; i<prevShares.length; i++) {
		    addFolder(prevShares[i].path, true);
		}
	    }
	}
	</script>
	<style>
	    .plus {
		float: left;
		width: 20px;
		text-align: right;
		text-decoration: none;
	    }
	</style>
    </head>
    <body onLoad="init()">
    	<div class="header"><img src="../mclogo.png" /></div>
	<div class="separ"></div>
	<div class="zone">
	    <div class="zoneContent">
		<a href="/mp9ctl/">Retour aux informations g&eacute;n&eacute;rales</a>
	    </div>
	</div>

<?php if (getOSType()=='windowsX') { ?>
    	<div class="zone">
	    <div class="zoneContent">
	    	Utilisez l'application <i>MediaCenter pour Windows</i> pour configurer les dossiers partag&eacute;s.
	    </div>
	</div>
    </body>
</html>
<?php exit(); } ?>    	
<?php
    /* Mode basique : ajout des dossiers manuellement */
    if (!$useFoldersTree) { ?>
	<div class="zone">
	    <div class="tab">Dossiers partag&eacute;s</div>
	    <div class="zoneContent">
	    	<table id="foldersList" class="list">
		    <thead>
			<tr><th>#</th><th>Chemin d'acc&egrave;s</th></tr>
		    </thead>
		    <tbody>
		    </tbody>
		</table>
	    </div>
	</div>
	<div class="zone">
	    <div class="tab">Ajouter un partage</div>
	    <form id="form" action="<?= $_PHPSELF ?>" method="POST" target="_blank" >
	    <input type="hidden" name="file" value="" />
	    <div class="zoneContent">
	    	Remarque : les fichiers et dossiers doivent &ecirc;tre accessibles en lecture.<br />
		<br />    
		<table class="list">
		    <tr><th>Chemin d'acc&egrave;s au dossier</th><td><input type="text" name="folderName" size="40" />&nbsp;&nbsp;<input id="addFolderButton" type="button" value="Ajouter" onClick="addFolder()" /></td></tr>
		</table>
		<!-- <input type="text" name="deviceName" size="40" /><input id="addDeviceButton" type="button" value="Ajouter" onClick="addDevice()" /> -->
<?php
    }
    /* Mode arborescence */
    else { ?>
	<div class="zone">
	    <div class="tab">S&eacute;lection des partages</div>
	    <form id="form" action="<?= $_PHPSELF ?>" method="POST" target="_blank" >
	    <input type="hidden" name="file" value="" />
	    <div class="zoneContent">
		Cochez les dossiers &agrave; partager<br /><input type="hidden" name="folderName" size="40" />
		<br />
<?php
    getDrivesContent();
    printFolder($folders);
} ?>
	    </div>
	</div>
	<div class="zone">
	    <div class="tab">Enregistrer la configuration</div>
	    <div class="zoneContent">
		<div id="createFile1">
		    <table class="list">
			<tr>
			    <th>Appuyez sur le bouton suivant et<br />enregistrez le fichier <b>shares.conf</b><br /> dans le dossier <b><?= $configFile1 ?></b>.</th>
			    <td><input type="button" value="G&eacute;n&eacute;rer le fichier de configuration 1/2" onClick="createFile('file1')"/></td>
			</tr>
		    </table>
		</div>
		<br />
		<div id="createFile2">
		    <table class="list">
			<tr>
			    <th>Appuyez sur le bouton suivant et<br />enregistrez le fichier <b>httpshares.conf</b><br />dans le dossier <b><?= $configFile2 ?></b>.</th>
			    <td><input type="button" value="G&eacute;n&eacute;rer le fichier de configuration 2/2" onClick="createFile('file2')"/></td>
			</tr>
		    </table>
		</div>
		<br />
		<div>
		    Relancez le serveur HTTP.
		</div>
	    </div>
	    <div id="foldersListValue" style="display: none"></div><div id="devicesListValue" style="display: none"></div>
	    </form>
	</div>
    </body>
</html>
